/**
 * Mock API 入口文件
 * 模拟 RESTful API 请求响应
 */

const userApi = require('./user');
const menuApi = require('./menu');
const orderApi = require('./order');
const messageApi = require('./message');
const notificationApi = require('./notification');

// 模拟延迟时间 (毫秒)
const MOCK_DELAY = 300;

/**
 * 模拟 API 请求
 * @param {string} url - API 路径
 * @param {string} method - 请求方法 (GET, POST, PUT, DELETE)
 * @param {object} data - 请求数据
 * @returns {Promise} - 返回 Promise 对象
 */
function request(url, method = 'GET', data = null) {
  return new Promise((resolve, reject) => {
    // 解析 API 路径
    const parts = url.split('/').filter(part => part);
    const resource = parts[0];
    const id = parts[1];
    const subResource = parts[2];
    
    // 构建请求对象
    const req = {
      url,
      method,
      data,
      params: { id, subResource }
    };
    
    // 根据资源类型分发请求
    let response;
    switch (resource) {
      case 'users':
        response = userApi.handleRequest(req);
        break;
      case 'menus':
        response = menuApi.handleRequest(req);
        break;
      case 'orders':
        response = orderApi.handleRequest(req);
        break;
      case 'messages':
        response = messageApi.handleRequest(req);
        break;
      case 'notifications':
        response = notificationApi.handleRequest(req);
        break;
      default:
        response = {
          code: 404,
          message: 'API not found',
          data: null
        };
    }
    
    // 模拟网络延迟
    setTimeout(() => {
      if (response.code >= 200 && response.code < 300) {
        resolve(response);
      } else {
        reject(response);
      }
    }, MOCK_DELAY);
  });
}

module.exports = {
  request
};
